<?php
class Article_model  extends Base_Model
{
    public function __construct()
    {
        $this->load->database();
    }

    public function getArices($data = array())
    {
        if (empty($data['id']) || !isset($data['id'])) {


            if (!empty($data['city'])) {
                $this->db->where('m.city', $data['city']);
            }

            if (!empty($data['country'])) {
                $this->db->where('m.country', $data['country']);
            }

            if (!empty($data['start'])) {
                $this->db->where('right(m.freeTimeDays,10)', $data['start']);
            }

            if (!empty($data['end'])) {
                $id = $this->all_track($data['end']);
                if (empty($id)) {
                    $id = array(0);
                }
                $this->db->where_in('m.id', $id);
            }

            if (!empty($data['touristCount'])) {
                $this->db->where('m.serviceMinPersons>=', $data['touristCount']);
            }

            if (!empty($data['people'])) {
                $this->db->where('m.serviceMaxPersons<=', $data['people']);
            }

            if (!empty($data['type'])) {
                $this->db->where('m.uid', 1);
            }

            if (!empty($data['age'])) {
                $this->db->where('u2i.userAge.uid', $data['age'] . '后');
            }

            if (!empty($data['gender'])) {
                $this->db->where('u.userGender', $data['gender']);
            }

            if (!empty($data['identity'])) {
                $this->db->where('u.identityName', $data['identity']);
            }

            if (!empty($data['language'])) {
                $key = 'cn';
                if ($data['language'] == 1) {
                    $key = 'cn';
                } else if ($data['language'] == 2) {
                    $key = 'fr';
                } else if ($data['language'] == 3) {
                    $key = 'en';
                }

                $this->db->where('u.' . $key, 1);
            }
            if (!empty($data['id'])) {
                $this->db->where('m.id', $data['id']);
            }
            if (!empty($data['guiderUid'])) {
                $this->db->where('m.uid', $data['guiderUid']);
            }
            $this->db->where('m.status', 'VALID');

            $this->db->join('user_v2 as u', 'u.uid = m.uid', 'left');
            $this->db->join('user_v2_userinfo as u2i', 'u2i.uid = m.uid', 'left');
            $count = $this->db->count_all_results('mod_activity as m');

        }


        if (!empty($data['city'])) {
            $this->db->where('m.city', $data['city']);
        }

        if (!empty($data['country'])) {
            $this->db->where('m.country', $data['country']);
        }

        if (!empty($data['start'])) {
            $this->db->where('right(m.freeTimeDays,10)', $data['start']);
        }


        if (!empty($data['end'])) {
            $id = $this->all_track($data['end']);
            if (empty($id)) {
                $id = array(0);
            }
            $this->db->where_in('m.id', $id);
        }

        if (!empty($data['touristCount'])) {
            $this->db->where('m.serviceMinPersons>=', $data['touristCount']);
        }

        if (!empty($data['people'])) {
            $this->db->where('m.serviceMaxPersons<=', $data['people']);
        }

        if (!empty($data['type'])) {
//            $this->db->where('m.uid', 1);
        }

        if (!empty($data['age'])) {
            $this->db->where('u2i.userAge.uid', $data['age'] . '后');
        }

        if (!empty($data['gender'])) {
            $this->db->where('u.userGender', $data['gender']);
        }

        if (!empty($data['identity'])) {
		    switch ($data['identity']){
 			    case 1:
					$this->db->where('u.identityName', '留学生');
					break;
				case 2:
					$this->db->where('u.identityName', '当地华人');
					break;
				case 3:
					$this->db->where('u.identityName', '外国人');
					break;
				default:

			}
		}	

        if (!empty($data['language'])) {
            $key = 'cn';
            if ($data['language'] == 1) {
                $key = 'cn';
            } else if ($data['language'] == 2) {
                $key = 'fr';
            } else if ($data['language'] == 3) {
                $key = 'en';
            }

            $this->db->where('u.' . $key, 1);
        }
        if (!empty($data['id'])) {
            $this->db->where('m.id', $data['id']);
        }
        if (!empty($data['guiderUid'])) {
            $this->db->where('m.uid', $data['guiderUid']);
        }
        $this->db->where('m.status', 'VALID');
        if (!empty($data['$offset']) && !empty($data['limit'])) {
            $this->db->limit($data['$offset'], $data['limit']);
        }
        $this->db->from('mod_activity as m');
        $this->db->join('user_v2 as u', 'u.uid = m.uid', 'left');
        $this->db->join('user_v2_userinfo as u2i', 'u2i.uid = m.uid', 'left');
        $query = $this->db->get()->result_array();

        if (!empty($data['id'])) {
            $re = $query;
        } else {
            $re['count'] = $count;
            $items = array();
            foreach ($query as $v) {
//                $items['name'] = $v['name'];
//                $items['orders'] = $v['orders'];
//                $items['thumb'] = $v['thumb'];
//                $items['summary'] = $v['summary'];
//                $items[''] = $v[''];
//                $items[''] = $v[''];
//                $items[''] = $v[''];

            }

            $re['articles'] = $query;


        }
        var_dump($re);
        die;
        return $re;
    }

    public function get_track_and_act($data = array())
    {
        $Where = '';
        if (!empty($data['guiderUid'])) {
            $Where .= ' AND uid ='.$data['guiderUid'];
        }

        if(!empty($data['cityId']))
        {
            $Where .= ' AND cityId ='.$data['cityId'];
        }
        $sql = '';
        if (!empty($data['sortkey'])) {
            $sorttype = empty($data['sorttype']) ? 'DESC' : $data['sorttype'];
            $sql = " ORDER BY {$data['sortkey']} {$sorttype}";
        }

        if (!empty($data['limit'])) {
            $offset = empty($data['offset']) ? "0" : $data['offset'];
            $sql .= "	LIMIT {$data['limit']} OFFSET {$offset}";
        }

        $sql1 = "SELECT
                    uid,
                    id,
                    city,
                    name,
                    thumb,
                    summary,
                    priceTotal,
                    changed,
                    created,
                    type,
                    zan`
                FROM
                    mod_track
                WHERE
                    status = 'VALID'".$Where;
        $sql2 = "SELECT
                    uid,
                    id,
                    city,
                    name,
                    thumb,
                    summary,
                    priceTotal,
                    changed,
                    created,
                    type,
                    zan`
                FROM
                    mod_activity
                WHERE
                    status = 'VALID'".$Where;
        $query = $this->db->query($sql1.' UNION ALL '.$sql2 . $sql);

        $items = array();
        foreach ($query->result_array() as $rs) {
            $item = array();
            $guider = $this->getUserInfoById($rs['uid']);
            $this->getUserInfoById($rs['uid']);
            $item['type'] = strtoupper($rs['type']);
            $item['id'] = $rs['id'];
            $item['thumb'] = $this->img($rs['thumb']);;
            $item['name'] = $rs['name'];
            $item['city'] = $rs['city'];
            $item['price'] = round($rs['priceTotal'] / 100, 2).'€';
            $item['summary'] = $rs['summary'];
            $item['userIcon'] = $this->img($guider['userIcon']);
            $item['realName'] = empty($guider['realName']) ? '' : $guider['realName'];
            $items[] = $item;
        }
        return $items;
    }



    /**
     * 搜索线路
     */
    public function track_act_search($data = array())
    {
        $w_sql1 = '';
        $w_sql2 = '';
        if (!empty($data['type'])) {
            $tr = $this->getTracks($data['type'],'TRACK');
            if(!empty($tr))
            {
                $trackIds = implode(',', $tr);
                $w_sql1 .= " AND m.id in (".$trackIds.")";
            }
            $acts = $this->getTracks($data['type'],'ACTIVITY');
            if(!empty($acts))
            {
                $actIds = implode(',', $acts);
                $w_sql2 .= " AND a.id in (".$actIds.")";
            }

        }

        if (!empty($data['city'])) {
            $w_sql1 .= " AND m.cityId = {$data['city']} ";
            $w_sql2 .= " AND a.cityId = {$data['city']} ";
        }

        if (!empty($data['start'])) {
            $id_start_m = $this->get_line_with_start($data['start'], 'mod_track');
            $id_start_a = $this->get_line_with_start($data['start'], 'mod_activity');
            if ($id_start_m!==NULL) {
                $id_start_m = implode(',', $id_start_m);
                $id_start_m = rtrim($id_start_m,',');
                $w_sql1 .= " AND m.id in (".$id_start_m.")";                
            }
            if ($id_start_a!==NULL) {
            	$id_start_a = implode(',', $id_start_a);
            	$id_start_a = rtrim($id_start_a,',');
            	$w_sql2 .= " AND a.id in (".$id_start_a.")";
            }
        }

        if (!empty($data['end'])) {
            $id_end_m = $this->get_line_with_end($data['end'], 'mod_track');
            $id_end_a = $this->get_line_with_end($data['end'], 'mod_activity');
            if ($id_end_m!==NULL) {
                $id_end_m = implode(',', $id_end_m);
                $id_end_m = rtrim($id_end_m,',');
                $w_sql1 .= " AND m.id in (".$id_end_m.")";
            }
            if ($id_end_a!==NULL) {
            	$id_end_a = implode(',', $id_end_a);
            	$id_end_a = rtrim($id_end_a,',');
            	$w_sql2 .= " AND a.id in (".$id_end_a.")";
            }
        }

        if(!empty($data['number']))
        {
            $w_sql1 .= " AND m.serviceMaxPersons >= '{$data['number']}'";
            $w_sql2 .= " AND a.serviceMaxPersons >= '{$data['number']}'";
        }

        if(!empty($data['age']))
        {
            $w_sql1 .= " AND u2i.userAge = '{$data['age']}后'";
            $w_sql2 .= " AND u2i.userAge = '{$data['age']}后'";
        }

        if(!empty($data['gender']))
        {
            $w_sql1 .= " AND u.userGender = '{$data['gender']}'";
            $w_sql2 .= " AND u.userGender = '{$data['gender']}'";
        }

        if(!empty($data['identity']))
        {
		    switch ($data['identity']){
			    case 1:
					$w_sql1 .= " AND u.identityName = '留学生' ";
					$w_sql2 .= " AND u.identityName = '留学生' ";
					break;
				case 2:
					$w_sql1 .= " AND u.identityName = '当地华人' ";
					$w_sql2 .= " AND u.identityName = '当地华人' ";
					break;
				case 3:
					$w_sql1 .= " AND u.identityName = '外国人' ";
					$w_sql2 .= " AND u.identityName = '外国人' ";
					break;
				default:
			} 
		}

        if(!empty($data['$language']))
        {
            if($data['$language'] == 1){
                $lkey = 'cn';
                $w_sql1 .= " AND u.{$lkey} = 1";
                $w_sql2 .= " AND u.{$lkey} = 1";
            }else if($data['$language'] == 2){
                $lkey = 'fr';
                $w_sql1 .= " AND u.{$lkey} = 1";
                $w_sql2 .= " AND u.{$lkey} = 1";
            }else if($data['$language'] == 3){
                $lkey = 'en';
                $w_sql1 .= " AND u.{$lkey} = 1";
                $w_sql2 .= " AND u.{$lkey} = 1";
            }


        }

        if(!empty($data['chuxing']))
        {
            if($data['chuxing']==1){
                $w_sql1 .= " AND m.trafficSupportCar = 1";
                $w_sql2 .= " AND a.trafficSupportCar = 1";
            }elseif($data['chuxing']==2){
                $w_sql1 .= " AND m.trafficSupportBus = 1";
                $w_sql2 .= " AND a.trafficSupportBus = 1";
            }
        }

        $sql = '';
        $orderSql = '';
        
        if(!empty($data['order']))
        {
            if($data['order'] == 1)
            {
                $orderSql= " priceTotal asc";
            }elseif ($data['order'] == 2)
            {
                $orderSql= " orders desc";
            }elseif ($data['order'] == 3)
            {
                $orderSql= " score desc";
            }
        }
        if(!empty($orderSql))
        {
            $sql .= ' ORDER BY '.$orderSql;
        }
        
        if (!empty($data['limit'])) {
        	$offset = empty($data['offset']) ? "0" : $data['offset'];
        	$sql .= " LIMIT {$data['limit']} OFFSET {$offset}";
        }

        $sql1 = "SELECT
                    `a`.`id`,
                    `a`.`city`,
                    `a`.`name`,
                    `a`.`thumb`,
                    `a`.`summary`,
                    `a`.`priceTotal`,
                    `a`.`type`,
					`a`.`orders`,
					`a`.`score`,
					`u`.`userName`,
                    `u2i`.`userIcon`
                FROM
                    `mod_activity` AS `a`
                LEFT JOIN `user_v2` AS `u` ON (`a`.`uid` = `u`.`uid`)
                LEFT JOIN `user_v2_userinfo` AS `u2i` ON (`u`.`uid` = `u2i`.`uid`)
                WHERE
                    `a`.`status` = 'VALID' {$w_sql2}
                ";

        $sql2 = "SELECT
                    `m`.`id`,
                    `m`.`city`,
                    `m`.`name`,
                    `m`.`thumb`,
                    `m`.`summary`,
                    `m`.`priceTotal`,
                    `m`.`type`,
					`m`.`orders`,
					`m`.`score`,
					`u`.`userName`,
                    `u2i`.`userIcon`
                FROM
                    `mod_track` AS `m`
                LEFT JOIN `user_v2` AS `u` ON (`m`.`uid` = `u`.`uid`)
                LEFT JOIN `user_v2_userinfo` AS `u2i` ON (`u`.`uid` = `u2i`.`uid`)
                WHERE
                    `m`.`status` = 'VALID' {$w_sql1}
                 ";
        //统计数量
        /*$count1 = "SELECT
			        count(*) as num
                FROM
                    `mod_activity` AS `a`
                LEFT JOIN `user_v2` AS `u` ON (`a`.`uid` = `u`.`uid`)
                LEFT JOIN `user_v2_userinfo` AS `u2i` ON (`u`.`uid` = `u2i`.`uid`)
                WHERE
                    `a`.`status` = 'VALID' {$w_sql2}
                ";
		$count2 = "SELECT
			        count(*) as num
                FROM
                    `mod_track` AS `m`
                LEFT JOIN `user_v2` AS `u` ON (`m`.`uid` = `u`.`uid`)
                LEFT JOIN `user_v2_userinfo` AS `u2i` ON (`u`.`uid` = `u2i`.`uid`)
                WHERE
                    `m`.`status` = 'VALID' {$w_sql1}
                 ";
	    //activity的数量
		$num1 = $this->db->query($count1)->row_array();
		//track的数量
        $num2 = $this->db->query($count2)->row_array();                                
		$num=$num1['num']+$num2['num'];*/

        $query = $this->db->query($sql1.' UNION ALL '.$sql2.$sql);
        $line = $query->result_array();
        $items = array();
        if(!empty($line))
        {
            foreach ($line as $q)
            {
                $item = array();
                $item['type'] = $q['type'];
                $item['id'] = $q['id'];
                $item['thumb'] = $this->img($q['thumb']);
                $item['name'] = $q['name'];
				$item['city'] = $q['city'];
				$item['userIcon'] = $this->img($q['userIcon']);
                $item['realName'] = $q['userName'];
                $item['summary'] = nl2br($q['summary']);
                $item['price'] = round($q['priceTotal']/100*1.1,2).'€';
                $items[] = $item;
            }

        }
        
        return $items;
    }


    public function all_track($date = null)
    {
        $query = $this->db->query("select id ,freetimeDays from mod_activity   WHERE status = VALID");
        $data = $query->result_array();
        $id = array();
        $time = strtotime($date);
        foreach ($data as $v) {
            $days = explode(',', $v['freetimeDays']);
            foreach ($days as $day) {
                $day_time = strtotime($day);
                if ($time > $day_time) {
                    $id[] = "'".$v['id']."'";
                    break;
                }
            }
        }

        return $id;

    }


    public function get_line_with_start($date = NULL, $table)
    {
    	if($table='mod_track'){
    		$Titem='freetimeDays';
    	}elseif($table='mod_activity'){
    		$Titem='freeTimeDays';
    	}else{
    		return NULL;
    	}
        $query = $this->db->query("select id,{$Titem} from {$table}   WHERE status = VALID");
        $data = $query->result_array();

        $id = array('0');
        $time = strtotime($date);
        foreach ($data as $v) {
        	if($table='mod_track'){
        		$v['freetimeDays']=trim($v['freetimeDays']);
        		$v['freetimeDays']=rtrim($v['freetimeDays'],',');
        		$days = explode(',', $v['freetimeDays']);
        	}else{
        		$v['freeTimeDays']=trim($v['freeTimeDays']);
        		$v['freeTimeDays']=rtrim($v['freeTimeDays'],',');
        		$days = explode(',', $v['freeTimeDays']);
        	}
            
            foreach ($days as $day) {
                $day_time = strtotime($day);
                if ($time < $day_time || $time == $day_time) {
                    $id[] = "'".$v['id']."'";
                    break;
                }
            }
        }
        
        return $id;
    }

    public function get_line_with_end($date = NULL, $table)
    {
    	if($table='mod_track'){
    		$Titem='freetimeDays';
    	}elseif($table='mod_activity'){
    		$Titem='freeTimeDays';
    	}else{
    		return NULL;
    	}
        $query = $this->db->query("select id ,freetimeDays from {$table}   WHERE status = VALID");
        $data = $query->result_array();
        $id = array('0');
        $time = strtotime($date);
        foreach($data as $v){
        	if($table='mod_track'){
        		$v['freetimeDays']=trim($v['freetimeDays']);
        		$v['freetimeDays']=rtrim($v['freetimeDays'],',');
        		$days = explode(',', $v['freetimeDays']);
        	}else{
        		$v['freeTimeDays']=trim($v['freeTimeDays']);
        		$v['freeTimeDays']=rtrim($v['freeTimeDays'],',');
        		$days = explode(',', $v['freeTimeDays']);
        	}

            foreach($days as $day){
                $day_time = strtotime($day);
                if($time > $day_time||$time==$day_time){
                    $id[] = "'".$v['id']."'";
                    break;
                }
            }
        }

        return $id;
    }



    public function getTracks($type,$targetType='TRACK')
    {
        $query  = $this->db->query("select targetNid from tiyu_categorygl   WHERE targetType = '{$targetType}'  AND categoryId = {$type}");
        $data = $query->result_array();
        $trackIds = array('0');
        if(!empty($data)) {
            foreach ($data as $t) {
                $trackIds[] = "'".$t['targetNid']."'";
            }

        }
        return $trackIds;
    }


    /**
     * @param $id
     * @return mixed
     * 获取单个详情
     */
    public function detail($id)
    {

        $this->db->where('id', $id);
        $this->db->from('mod_activity');
        $query = $this->db->get()->row_array();

        if(!empty($query['uid']))
        {
            $guider = $this->getUserInfoById($query['uid']);
        }else{
            return false;
        }
        //图片墙
        $query['images']=trim($query['images']);
        $query['images']=rtrim($query['images'],'|');
        $Imgs = explode('|',$query['images']);
        $imgnum=count($Imgs);
        if($imgnum>3){
        	$Imgs=array_slice($Imgs, 0, 3);
        }
        $ret=array();
        if(!empty($Imgs))
        {
            foreach ($Imgs as $k=>$img)
            {
                $ret[$k]['image'] = $this->img($img);
                $ret[$k]['name'] = $query['name'];
            }
            $Imgs=array_values($ret);
        }
        
		$item['id'] = $query['id'];
		//玩伴id，聊天对象
		$item['rev_id']=$query['uid'];
		$item['type'] = $query['type'];
		$item['name'] = $query['name'];
        $item['city'] = $query['city'];
        $item['serviceMaxPersons'] = $query['serviceMaxPersons']."人";
        $item['duration']=$query['hours']."小时";
        //背景图
        $item['bannerUrl']=$this->img($query['bannerUrl']);
        //照片墙
        $item['imageswall'] = $Imgs;
        $item['imagenum']=$imgnum;
        //基本信息
        $item['userIcon'] = $this->img($guider['userIcon']);
        $item['realName'] = $guider['realName'];
        //$item['identityActive'] = $guider['identityActive'];
        //$item['telActive'] = $guider['telActive'];
        //$item['resideCity'] = $guider['resideCity'];
        //$item['resideTime'] = $guider['resideTime'];
        $item['userAge'] = $guider['userAge'];
		
		if($guider['userGender']=='m')
			$item['userGender'] = '男';
		elseif($guider['userGender']=='f')
			$item['userGender'] = '女';
		else
			$item['userGender'] = '';

        $item['identityName'] = $guider['identityName'];
        //学校、专业、工作领域
        $item['major'] = $guider['major'];
        $item['school'] = $guider['school'];
        $item['job'] = $guider['job'];
        //玩伴介绍
        $item['introduction'] = nl2br($guider['introduction']);
        //集合地点
        $item['location'] = $query['location'];
        $item['lat'] = $query['lat'];
        $item['lng'] = $query['lng'];
        //出行方式
        if($query['trafficSupportBus']==1)
        {	$item['chuxing']='公共交通';}
        elseif($query['trafficSupportCar']==1)
        {   $item['chuxing']='公共交通';}
        else {$item['chuxing']='自行选择';}
        //路线简介
        $item['summary'] = nl2br($query['summary']);
        //行程描述
        $item['todolist'] = nl2br($query['todolist']);
        //价格详情
        $item['serviceIcon'] = $this->img('/resource/images/service-icon.png');
        $item['priceService'] = round($query['priceService']/100,2).'€';
        $item['descService'] = '服务费用是除固定旅行成本(餐饮、交通、票务等)外给予玩伴的费用，其中包括陪游、讲解、行程安排和咨询等服务，价格不会随游客人数浮动';
        
        return $item;
//        var_dump($item);die;

    }
    public function getbyid($id)
    {
        $this->db->where('id', $id);
        $this->db->from('mod_activity');
        $query = $this->db->get()->row_array();
        return $query;
    }
    public function getimagewall($id)
    {
    	$this->db->select('images,name');
    	$this->db->where('id', $id);
    	$this->db->from('mod_activity');
    	$query = $this->db->get()->row_array();
    	
    	$query['images']=trim($query['images']);
    	$query['images']=rtrim($query['images'],'|');
    	$Imgs = explode('|',$query['images']);
    	//$imgnum=count($Imgs);
    	
    	$ret=array();
    	if(!empty($Imgs))
    	{
    		foreach ($Imgs as $k=>$img)
    		{
    			$ret[$k]['image'] = $this->img($img);
    			$ret[$k]['name'] = $query['name'];
    		}
    	}
    	return array_values($ret);
    }

}
